<template>
    <n-alert v-if="alertShow" :title="title" :type="type" :bordered="false">
        <div v-if="isLoading" class="loading-container">
            <n-spin size="small" type="info" stroke-width="10" stroke="#2080f0"/>
            <span class="loading-text">&nbsp;正在验证资源配置，请稍候...</span>
        </div>
        <div v-else>
            {{ errMsg }}
        </div>
    </n-alert>
    <n-form
        style="margin-top: 24px"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-placement="left"
        label-width="140"
        require-mark-placement="right-hanging"
        :disabled="formDisabled"
    >
        <n-form-item label="资源类型" path="type">
            <jb-select v-model:value="form.type" url="/VDB/list" placeholder="请选择资源类型" label-field="name"
                       value-field="sn">
            </jb-select>
        </n-form-item>

        <n-form-item label="资源名称" path="name">
            <n-input v-model:value="form.name" placeholder="请输入资源名称"></n-input>
        </n-form-item>
        <n-form-item label="Embedding类型" path="embedding">
            <jb-select v-model:value="form.embedding" :url="embeddingUrl" placeholder="请选择embedding类型"
                       label-field="name"
                       value-field="sn">
            </jb-select>
        </n-form-item>

        <n-form-item label="url" path="url">
            <n-input v-model:value="form.url" placeholder="请输入url"></n-input>
        </n-form-item>
        <n-form-item label="用户名" path="username">
            <n-input v-model:value="form.username" placeholder="请输入用户名"></n-input>
        </n-form-item>
        <n-form-item label="密码" path="password">
            <n-input v-model:value="form.password" type="password" placeholder="请输入密码"
                     show-password-on="click"></n-input>
        </n-form-item>
        <n-form-item label="数据库名称" path="databaseName">
            <n-input v-model:value="form.databaseName" placeholder="请输入数据库名称"></n-input>
        </n-form-item>
        <n-form-item label="检测配置">
            <jb-btn type="primary" ghost @click="check()" :loading="isLoading"
                    :disabled="isLoading" icon="">
                <jb-icon icon="ri:shield-check-line" :local="true" width="20" color="#18a058"></jb-icon>
                <span>&nbsp;检测当前配置是否正确</span>
            </jb-btn>
        </n-form-item>
    </n-form>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {JBoltApi} from '@/service/request'

const props = defineProps({
    id: {
        type: String
    }
})

const embeddingUrl = computed(() => {
    if (form.value.type == 'TENCENT') {
        return '/embeddingResource/listAllEnabledTypeWithTencent';
    }
    return '/embeddingResource/listAllEnabledType';
})
const title = ref('资源配置正确')
const type = ref('success')
const errMsg = ref('')
const alertShow = ref(false)
const isLoading = ref(false)
const formDisabled = ref(false) // 新增：表单禁用状态
const formRef = ref(null)
const items = ref(null)

const form = ref({
    id: '',
    name: '',
    type: null,
    embedding: null,
    embeddingResourceId: '',
    url: '',
    username: '',
    password: '',
    databaseName: '',
    enable: true,
    createTime: '',
    timeout: ''
})


const rules = {
    type: {
        required: true,
        message: '请选择资源类型',
        trigger: 'change'
    },
    embedding: {
        required: true,
        message: '请选择Embedding类型',
        trigger: 'change'
    },
    name: {
        required: true,
        pattern: /\S/, // 至少有一个非空白字符
        message: '请输入资源名称',
        trigger: 'change'
    },
    url: {
        required: true,
        pattern: /\S/, // 至少有一个非空白字符
        message: '请输入url',
        trigger: 'change'
    },
    username: {
        required: true,
        pattern: /\S/, // 至少有一个非空白字符
        message: '请输入用户名',
        trigger: 'change'
    },
    password: {
        required: true,
        pattern: /\S/, // 至少有一个非空白字符
        message: '请输入密码',
        trigger: 'change'
    },
    databaseName: {
        required: true,
        pattern: /\S/, // 至少有一个非空白字符
        message: '请输入数据库名称',
        trigger: 'change'
    }
}

const embeddingOptions = ref([])

// 加载编辑数据
async function loadEditData() {
    if (props.id) {
        const {result} = await JBoltApi.get(`/VDBResource/getById/${props.id}`)
        if (result) {
            form.value = result.data
        }

    }
}

defineExpose({
    submit
})

async function submit(fun) {
    console.log('提交表单', form.value)
    await formRef.value?.validate()
    console.debug('提交表单', form.value)
    let url = props.id ? '/VDBResource/update' : '/VDBResource/add'
    if (props.id) {
        await JBoltApi.put(url, form.value)
    } else {
        await JBoltApi.tryPost(url, form.value)
    }
    if (fun) {
        fun()
    }

    return true
}

// 检查资源
async function check() {
    // 表单校验
    try {
        await formRef.value?.validate()
    } catch (error) {
        return // 表单校验失败，直接返回
    }

    // 设置加载状态
    isLoading.value = true
    formDisabled.value = true

    // 显示加载中的提示
    alertShow.value = true
    type.value = 'info'  // 使用info类型，显示为蓝色
    title.value = '正在检测资源配置'
    errMsg.value = '请稍候...'

    JBoltApi.tryPost('/VDBResource/check', form.value).then(res => {
        if (res.data.result) {
            type.value = 'success'
            title.value = '资源配置正确'
            errMsg.value = '所有配置验证通过！'
        } else {
            type.value = 'error'
            title.value = '资源配置异常'
            errMsg.value = res.data.msg
        }
    }).catch((error) => {
        console.error(error)
        type.value = 'error'
        title.value = '请求异常'
        errMsg.value = '网络请求失败，请稍后重试'
    }).finally(() => {
        isLoading.value = false
        formDisabled.value = false
    })
}


onMounted(() => {
    if (props.id) {
        loadEditData()
    }

})

</script>

<style scoped lang="scss">
.text_tip {
    font-size: 12px;
    color: #999;
}

</style>